<template>
  <div class="wrap">
    <el-form
        class="loginForm"
        :model="resident"
        :rules="loginFormRules"
        ref="loginFormRef"
        label-position="left"
    >
      <el-form-item label="手机号" prop="phone1">
        <el-input v-model="resident.phone1"></el-input>
      </el-form-item>
      <el-form-item label="手机验证码" prop="verificationCode">
        <el-input v-model="verificationCode">
          <template slot="append">
            <el-button v-if="isButtonDisabled":disabled="isClickButton" @click="disableButtonAndShowSpinner">
              <span v-if="isClickButton">
                {{countdown}}秒后再次获取
              </span>
              <span v-else>
                  发送验证码
              </span>
            </el-button>
          </template>
        </el-input>
      </el-form-item>
      <el-form-item class="btns">
        <el-button type="primary" @click="login">登录</el-button>
      </el-form-item>
    </el-form>
    <el-dialog
        title="旋转图片验证"
        :visible.sync="dialogVisible"
        width="50%"
        @close="dialogVisible = false"
    >
      <div class="container">
        <div class="image-wrapper">
          <div class="image-box" :style="{
        transform: `rotate(${rotateDegrees}deg)`,
        background: `url(${imageSrc}) no-repeat center / 100% auto`,
    }"></div>
          <input type="range" min="0" max="360" v-model="rotationValue" @mouseup="checkRotation" @touchend="checkRotation">
        </div>
        <div class="message" v-if="showMessage">{{ mes}}</div>
        <div class="degree-info">当前图片度数: {{ rotateDegrees }}</div>
        <div class="degree-info">初始化图片度数: {{ firstRotateDegrees }}</div>
        <div class="degree-info">当前滚动条度数: {{ rotationValue }}</div>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
export default {
  data() {
    // 验证手机号是否合法
    var checkMobile = (rules, value, callback) => {
      const regMobile = /^(0|86|17951)?(13[0-9]|15[0123456789]|17[678]|18[0-9]|14[57])[0-9]{8}$/;
      if (regMobile.test(value) == true) {
        return callback();
      } else {
        callback(new Error("请输入合法的手机号"));
      }
    };
    // 验证输入的手机号验证码是否和存储的验证码相同
    var checkPhoneCode = (rules, value, callback) => {
      if (value == this.contenttext) {
        return callback();
      } else {
        callback(new Error("验证码错误"));
      }
    };
    return {
      // 表单
      resident: {
        phone1: "",
      },
      verificationCode: "", //表单中展示的验证码
      contenttext: "", //向手机号发送的随机验证码
      isButtonDisabled: true, //判断展示‘获取验证码’或‘倒计时’
      isClickButton: false, //是否点击获取验证码按钮
      count: "", //倒计时时间
      // 验证规则
      loginFormRules: {
        phone1: [
          { required: true, message: "请输入手机号", trigger: "blur" },
          { validator: checkMobile, trigger: "blur" },
        ],
        verificationCode: [
          { required: true, message: "请输入手机验证码", trigger: "blur" },
          { validator: checkPhoneCode, trigger: "blur" },
        ],
      },
      dialogVisible: false,
      rotateDegrees: 0, // 随机旋转角度
      firstRotateDegrees: Math.floor(Math.random() * 360), // 随机旋转角度
      rotationValue:0,
      showMessage: false,
      mes: '',
      imageSrc: 'https://img2.baidu.com/it/u=3344911223,3409692090&fm=253&fmt=auto&app=138&f=JPEG?w=500&h=313',
      isLogin:false,
      //限时任务
      countdown: 0, // 剩余秒数
      countdownInterval: null, // 存储setInterval的ID，以便可以清除它
    };
  },
  methods: {
    // 获取手机验证码
    getCode() {
      console.log(this.resident.phone1);
      if (this.isLogin==true){
        //验证通过，调用axios获取验证码
        this.$axios.post("/web/sendCode",this.resident).then(res=>{
            this.contenttext=res.data.code;
        });
      }
      else{
        return;
      }
    },
    //实现登录
    login(){
      if (this.verificationCode==this.contenttext){
        this.$axios.post("/web/loginWithPhone",null,{params:{phone:this.resident.phone1,value:false}}).then(res=>{
          if (res.data.code==1001){
            this.$message.error("手机号未注册");
          }
          else{
            window.localStorage.setItem("webToken",res.data.webToken);
            window.localStorage.setItem("resident",JSON.stringify(res.data.resident));
            this.$router.push("/");
          }
        });
      } else{
        this.$message.error("验证码输入错误");
      }
    },
    disableButtonAndShowSpinner(){
      this.dialogVisible=true;
      this.isClickButton=true;
      this.countdown = 60;
      this.countdownInterval = setInterval(() => {
        if(this.countdown > 0){
          this.countdown--;
        }else{
          clearInterval(this.countdownInterval);
          this.isClickButton=false;
          this.countdown=0;
        }
      },1000)
    },

    //旋转图片验证
    checkRotation() {
      if( Math.abs(360 - (this.rotateDegrees)) <= 10) {

        this.mes = '验证成功';
        //隐藏验证窗口
        this.dialogVisible=false;
        //去登陆
        this.isLogin=true;
        this.getCode();;
      } else {
        this.mes = '验证失败';
        this.isLogin=false;
        this.dialogVisible=false;
      }
      this.showMessage = true;
      this.rotationValue = 0;
      setTimeout(() => {
        this.firstRotateDegrees = Math.floor(Math.random() * 360);
        this.rotateDegrees = this.firstRotateDegrees;
        this.showMessage = false;
      }, 2000);
    },
    slideEvent(){
    },
  },
  created() {
    this.rotateDegrees = this.firstRotateDegrees;
  },
  watch: {
    rotationValue(newVal,oldVal) {
      if (!this.showMessage){
        this.rotateDegrees = this.rotateDegrees + (newVal-oldVal);
      }
    },
  }
};
</script>
<style scoped>
.loginForm {
  width: 300px;
  margin: 0 auto;
}
.btns {
  text-align: right;
}
.container {
  width: 200px;
  height: 300px;
  text-align: center;
}

.image-wrapper {
  position: relative;
  height: 250px;
  overflow: hidden;
}

.image-box {
  position: absolute;
  top: 0px;
  left: 0px;
  right: 0;
  bottom: 0;
  margin: auto;
  width: 180px;
  height: 180px;

}

.rotation-control {
  width: 90%;
  margin-top: 20px;
}

.image-box img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.message {
  margin-top: 20px;
  padding: 10px;
  background-color: #333;
  color: #fff;
  border-radius: 5px;
}
</style>